<template>
	<div class="question-list-container">
		<div class="tool-bar">
			<Search :queryMode="queryMode" @searchData="handleSearch"  />
			<div>
				<el-button v-if="multipleSelection.length > 0" class="button" size="small" @click="handlerDeleteSelection">删除</el-button>
				<el-button v-if="multipleSelection.length > 0" class="button" size="small" @click="handleEditSelection">分类</el-button>
				<el-button type="primary" size="small" class="button" @click="handleCreate">新增</el-button>
				<el-button size="small" class="button" @click="showImportKb = true">导入</el-button>
			</div>
		</div>
		<div class="table-section">
			<Table :tableData="questionList" @selection-change="handleSelectionChange" ref="multipleTable">
				<template v-slot:name>
					<el-table-column prop="name" label="问题标题" align="center" width="160" :show-overflow-tooltip="false">
						<template slot-scope="scope">
							<!-- <div class="question-name">{{ scope.row.name }}</div> -->
							<el-popover trigger="hover" placement="top" width="800" :disabled="!scope.row.hasScroll">
								<p>{{ scope.row.name }}</p>
								<div slot="reference" class="name-wrapper">
									<div class="question-name" :id="`kb-question-name-${scope.row.id}`">{{ scope.row.name }}</div>
								</div>
							</el-popover>
						</template>
					</el-table-column>
				</template>
				<template v-slot:answer>
					<el-table-column prop="answer" label="答案内容" align="center" width="200">
						<template slot-scope="scope">
							<div v-if="scope.row.type === 'text'" class="answer" @click="() => showContent(scope.row.answer)">{{ scope.row.answer }}</div>
							<el-image v-else-if="scope.row.type === 'image'" style="width: 50px; height: 50px" :src="scope.row.answer" :preview-src-list="[scope.row.answer]"> </el-image>
							<el-link v-else type="primary" @click="handleOpenLink(scope.row)">{{ scope.row.fileName }}</el-link>
						</template>
					</el-table-column>
				</template>
				<template v-slot:btn>
					<el-table-column width="150px" align="center" label="操作">
						<template slot-scope="scope">
							<el-button size="small" type="primary" @click="edit(scope.$index, scope.row)">编辑</el-button>
							<el-button size="small" type="danger" @click="remove(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</template>
			</Table>
		</div>

		<div class="page">
			<PageSize :pages="checkData" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
		</div>

		<CreateQuestion
			v-if="createQuestionVisible"
			:visible="createQuestionVisible"
			:groupList="groupList"
			:question="curQuestion"
			@close="createQuestionVisible=false"
			@confirm="handleCreateQuestionConfirm"
		>
		</CreateQuestion>

		<el-dialog title="答案内容详情" :visible.sync="dialogVisible" width="80%" :before-close="handleClose">
			<div class="answer-wrapper">
				<p>{{ curAnswer }}</p>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 导入知识库 -->
		<ImportKb v-if="showImportKb" :show="showImportKb" @close="showImportKb = false" @imported="importKbSuccess" />
		<VideoPreview v-if="showVideoPreview" :isShow="showVideoPreview" :url="curAnswer" @close="showVideoPreview = false" />
	</div>
</template>
<script>
import Table from './Table.vue';
import PageSize from '../components/PageSize.vue';
import CreateQuestion from './CreateQuestion.vue';
// import { questionsMock } from './mock';
import { deleteKnowledgeBase, getKnowledgeBaseList, createKnowledgeBase, updateKnowledgeBase, batchDeleteKnowledgeBase } from '@/api/api';
import Search from './Search.vue';
import ImportKb from './ImportKb.vue';
import { findAndConcatNamesById } from '@/utils/MyVueUtil.js';
import VideoPreview from '../components/VideoPreview.vue';
import { appendToken, removeToken } from '@/utils/tool';

export default {
	components: {
		Table,
		PageSize,
		CreateQuestion,
		Search,
		ImportKb,
		VideoPreview
	},
	props: {
		group: {
			type: Object,
			default: () => ({})
		},
		groupList: {
			type: Array,
			default: () => []
		},
		queryMode: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			questionList: {
				showCheck: true,
				checkedGroup: true,
				tooltipEffect: 'light',
				sort: false,
				// 问题标题、答案内容、分类、创建时间、更新时间、搜索量、操作（编辑、删除）
				tableHead: [
					// {
					// 	label: '问题',
					// 	prop: 'name',
					// 	tooltip: true
					// },
					// {
					// 	label: '回答内容',
					// 	prop: 'answer',
					// 	tooltip: true,
					// 	width: 200,
					// 	isCustom: true
					// },
					{
						label: '分类',
						prop: 'categoryName',
						tooltip: true,
						className: 'category-name'
					},
					{
						label: '创建时间',
						prop: 'createdAt'
					},
					{
						label: '更新时间',
						prop: 'updatedAt'
					},
					{
						label: '搜索量',
						prop: 'pageView',
						width: 50
					}
					// {
					// 	label: '评分',
					// 	prop: 'score',
					// 	width: 50
					// },
					// {
					// 	label: '是否公开',
					// 	prop: 'isPublicText',
					// 	width: 50
					// }
				],
				tableConent: [],
				showIndex: false,
				multipleSelection: []
			},
			checkData: {
				page: 1,
				pageSize: 10,
				total: 0
			},
			createQuestionVisible: false,
			curQuestion: {},
			dialogVisible: false,
			curAnswer: '',
			multipleSelection: [],
			showImportKb: false,
			curSearchName: '',
			showVideoPreview: false
		};
	},
	watch: {
		group: {
			handler(val) {
				console.log(val);
				if (val.id !== undefined) {
					this.checkData.page = 1;
					this.getKnowledgeBaseList();
				}
			},
			deep: true
		},
		queryMode: {
			handler(val) {
				console.log('queryMode', val);
				if (val !== 'search') {
					this.curSearchName = '';
				}
			},
		}
	},
	mounted() {
		// this.getKnowledgeBaseList();
		// this.questionList.tableConent.map(item => {
		// 	item.categoryName = findAndConcatNamesById(this.groupList, item.categoryId);
		// });
		// this.$nextTick(() => {
		// 	this.checkScroll();
		// });
	},
	methods: {
		// 变更页数
		changePageSize(val) {
			this.checkData.pageSize = val;
			this.checkData.page = 1;
			this.getKnowledgeBaseList();
		},
		// 变更页码
		changeCurrentPage(val) {
			this.checkData.page = val;
			this.getKnowledgeBaseList();
		},
		// 删除问题
		remove(index, row) {
			console.log('remove', index, row);
			this.$confirm('此操作将永久删除该问题, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.deleteKnowledgeBase(row);
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
		},
		// 创建问题
		handleCreate() {
			console.log('create');
			this.curQuestion = {};
			this.createQuestionVisible = true;
		},
		// 编辑问题
		edit(index, row) {
			console.log(index, row);
			if (row.type !== 'text') {
				row.answer = removeToken(row.answer);
			}
			this.curQuestion = row;
			this.createQuestionVisible = true;
		},
		// 获取问题列表
		getKnowledgeBaseList() {
			// if (this.group.id === undefined) {
			// 	return;
			// }
			const param = {
				page: this.checkData.page,
				pageSize: this.checkData.pageSize
			};
			if (this.curSearchName) {
				param.name = this.curSearchName;
			} else {
				param.categoryId = this.group.id === 'all' ? '' : this.group.id;
			}
			getKnowledgeBaseList(param)
				.then(res => {
					console.log('getKnowledgeBaseList', res.data.data);
					const { data, count } = res.data.data;
					this.questionList.tableConent = data.map(item => {
						return {
							...item,
							isPublicText: item.isPublic ? '是' : '否',
							updatedAt: item.updatedAt ? this.$moment(item.updatedAt).format('YYYY-MM-DD HH:mm:ss') : '-',
							createdAt: item.createdAt ? this.$moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss') : '-', // 日期格式化
							hasScroll: false,
							categoryName: findAndConcatNamesById(this.groupList, item.categoryId),
							answer: item.type === 'text' ? item.answer : appendToken(item.answer)
						};
					});
					this.checkData.total = count;
					this.$nextTick(() => {
						this.checkScroll();
					});
				})
				.catch(err => {
					console.log(err);
				});
		},
		// 删除问题
		deleteKnowledgeBase(data) {
			deleteKnowledgeBase(data.id)
				.then(res => {
					console.log(res);
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
					this.getKnowledgeBaseList();
				})
				.catch(err => {
					console.log(err);
				});
		},
		// 创建问题
		createKnowledgeBase(data) {
			createKnowledgeBase(data)
				.then(res => {
					console.log('createKnowledgeBase', res);
					this.createQuestionVisible = false;
					// this.getKnowledgeBaseList();
					this.$emit('created', res.data?.data);
				})
				.catch(err => {
					console.log(err);
					if (err.code === 1002) {
						// show error message
						this.$message({
							type: 'error',
							message: '问题已存在!'
						});
					} else {
						// show error message
						this.$message({
							type: 'error',
							message: '创建失败!'
						});
					}
				});
		},
		// 创建问题
		handleCreateQuestionConfirm(form) {
			// this.createQuestionVisible = false;
			console.log(form);
			let categoryId = 0;
			if (form.catagory?.length > 0) {
				categoryId = form.catagory[form.catagory.length - 1];
			}
			const data = {
				answer: form.answer || form.resouceUrl,
				name: form.question,
				categoryId: categoryId,
				type: form.answerType,
				fileName: form.resouce[0] ? form.resouce[0].name : ''
			};
			if (this.curQuestion.id) {
				data.id = this.curQuestion.id;
				this.updateKnowledgeBase(data);
			} else {
				this.createKnowledgeBase(data);
			}
		},
		// 更新问题
		updateKnowledgeBase(data) {
			updateKnowledgeBase(data)
				.then(res => {
					console.log(res);
					this.createQuestionVisible = false;
					this.getKnowledgeBaseList();
				})
				.catch(err => {
					console.log(err);
				});
		},
		handleOpenLink(data) {
			const { type, answer } = data;
			if (type === 'pdf') {
				window.open(answer, '_blank');
			} else if (type === 'video') {
				this.curAnswer = answer;
				this.showVideoPreview = true;
			}
		},
		showContent(content) {
			this.curAnswer = content;
			this.dialogVisible = true;
		},
		// 多选
		handleSelectionChange(val) {
			console.log('handleSelectionChange', val);
			this.multipleSelection = val;
		},
		// 查询
		handleSearch(data) {
			console.log('handleSearch', data);
			this.curSearchName = data;
			this.multipleSelection = [];
			this.questionList.tableConent = [];
			this.$emit('search', data);
			this.checkData.page = 1;
			this.getKnowledgeBaseList();
		},
		// 批量删除
		handlerDeleteSelection() {
			this.$confirm('此操作将永久删除选择的问题, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.batchDeleteKnowledgeBase(this.multipleSelection);
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
		},
		// 批量编辑问题分类
		handleEditSelection() {
			this.$emit('edit-catagory', this.multipleSelection);
		},
		// 导入问题
		importKbSuccess() {
			this.showImportKb = false;
			this.getKnowledgeBaseList();
		},
		// 判断问题标题是否需要显示tooltip
		checkScroll() {
			this.questionList.tableConent.map(item => {
				const el = document.getElementById(`kb-question-name-${item.id}`);
				console.log('checkScrollX', item.id, el);

				if (el) {
					item.hasScroll = el.scrollWidth > el.clientWidth || el.scrollHeight > el.clientHeight;
				}
			});
		},
		// 批量删除
		batchDeleteKnowledgeBase(data) {
			// "ids":[9,10]
			const ids = data.map(item => {
				return item.id;
			});
			batchDeleteKnowledgeBase({ ids: ids })
				.then(res => {
					console.log(res);
					this.$refs.multipleTable.clearSelection();
					this.getKnowledgeBaseList();
				})
				.catch(err => {
					console.log(err);
					this.$message.error('删除失败');
				});
		},
		// 取消多选
		clearSelection() {
			this.$refs.multipleTable.clearSelection();
		},
		clearSearchName() {
			this.curSearchName = '';
		}
	}
};
</script>

<style scoped lang="less">
.question-list-container {
	padding: 20px;
	box-sizing: border-box;
	width: 100%;
	height: 100%;

	.tool-bar {
		display: flex;
		align-items: center;
		margin-bottom: 20px;
		justify-content: space-between;

		.button {
			cursor: pointer;
		}
	}

	.root-node {
		margin-top: 10px;
	}

	.page-size {
		padding-top: 20px;
	}

	.table-section {
		height: calc(100% - 100px);
		overflow-y: auto;
	}

	.answer {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 3;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: pre-wrap;
		cursor: pointer;
	}
	.question-name {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 3;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: pre-wrap;
	}

	.category-name {
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.answer-wrapper {
		overflow-y: auto;
		height: 600px;
		max-height: calc(100vh - 300px);
	}
}
</style>
<style lang="less">
.question-list-container {
	.el-tree {
		overflow: auto;
		height: calc(100% - 100px);

		.el-tree-node {
			margin-top: 10px;
		}
	}

	.category-name {
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.el-popover {
		background: #303133; /* 暗色背景 */
		color: white; /* 文字颜色 */
		border-color: #303133; /* 边框颜色，如果需要 */
		/* 其他自定义样式 */
	}

	.el-image__error {
		font-size: 12px;
	}

	.el-dialog {
		margin-top: 5% !important;
	}

}
</style>
